package vn.edu.saigontech.ncms.service.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.bookstore.ImportReceiptDetail;
import vn.edu.saigontech.ncms.model.bookstore.Item;
import vn.edu.saigontech.ncms.service.ImportReceiptDetailService;

@SuppressWarnings("unchecked")
public class ImportReceiptDetailServiceImpl extends HibernateGenericService<ImportReceiptDetail, Long> implements ImportReceiptDetailService {

	@Override
	public List<Item> findByItemId(Long itemId) {
		Criteria criteria = this.createCriteria();
		criteria.createCriteria("item").add(Restrictions.eq("id", itemId));
		return criteria.list();
	}
	
	@Override
	public int sumOfImport(Item item, Date toDate, boolean includeToDate) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("item", item));

		Criteria receiptCriteria = criteria.createCriteria("importReceipt");
		if (includeToDate) {
			receiptCriteria.add(Restrictions.le("date", toDate));
		} else
			receiptCriteria.add(Restrictions.lt("date", toDate));

		criteria.setProjection(Projections.sum("quantity"));
		List<?> list = criteria.list();
		Object value = list.get(0);
		if(value != null) {
			return (Integer) value;
		}
		return 0;
	}

	@Override
	public int sumOfImport(Item item, Date fromDate, Date toDate) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("item", item));

		Criteria receiptCriteria = criteria.createCriteria("importReceipt");
		receiptCriteria.add(Restrictions.ge("date", fromDate));
		receiptCriteria.add(Restrictions.le("date", toDate));
		
		criteria.setProjection(Projections.sum("quantity"));
		List<?> list = criteria.list();
		Object value = list.get(0);
		if(value != null) {
			return (Integer) value;
		}
		return 0;
	}
}